<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/12/7
 * Time: 10:03
 */

namespace app\storage\service;

use app\storage\model\UserModel;
use app\storage\model\RoleModel;
use think\exception\DbException;
use think\response\Json;

class UserService extends CommonService
{

    /**
     * @param string $id
     * @return Json
     * @throws DbException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserInfo($id = '')
    {
        $userId = empty($id) ? session('ADMIN_ID') : $id;
        $userInfo = UserModel::get($userId, 'RoleUser.Role');
        $roleModel = new RoleModel();
        $parentRole = $roleModel->column('id,name');
        $userModel = new UserModel();
        if ($userInfo->getData('parent_id') == 0 && $userInfo->getData('user_login') === 'admin') {
            $where = [];
        }else{
            $where['id'] = $userId;
        }
        $result = $userModel->where($where)->with('StaffStorage.Storage,RoleUser.Role')->select();
        $result = count($result) ? $result->toArray() : [];
        foreach ($result as $k => $item) {
            if (is_array($item['staff_storage'])) {
                $result[$k]['parent_name'] = empty($parentRole[$item['parent_id']]) ? '' : $parentRole[$item['parent_id']];
                $result[$k]['storage_name'] = [];
                foreach ($item['staff_storage'] as $value) {
                    if($value['status'] == 1){
                        $result[$k]['storage_name'][] = $value['name'];
                    }
                }
                implode('、', $result[$k]['storage_name']);
            }
        }
        if (!empty($id) && count($result)) {
            $result = $result[0];
        }
        return $result;
    }
}